package com.blacktry.controller;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blacktry.mapper.BookMapper;
import com.blacktry.pojo.Book;
import com.blacktry.pojo.Lend;
import com.blacktry.pojo.RespBean;
import com.blacktry.pojo.User;
import com.blacktry.service.BookService;
import com.blacktry.service.LendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author blackTry
 * @since 2021-01-31
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;


    @PostMapping("/save")
    public RespBean save(@RequestBody Book book){
        if(bookService.save(book)){
            return RespBean.success("添加成功！");
        }else{
            return RespBean.error("添加失败！");
        }
    }

    @DeleteMapping("/delete/{bookId}")
    public RespBean delete(@PathVariable("bookId") Integer bookId){
        if(bookService.removeById(bookId)){
            return RespBean.success("删除成功！");
        }else{
            return RespBean.error("删除失败！");
        }
    }

    @Autowired
    private LendService lendService;

    // 归还书：空闲数量+1
    @PutMapping("/back/{bookId}/{serNum}")
    public RespBean back(@PathVariable("bookId") Integer bookId,@PathVariable("serNum")Integer serNum){
        Book book = bookService.getById(bookId);
        book.setLeisure(book.getLeisure()+1);
        Lend lend = lendService.getById(serNum);
        lend.setState(1);
        lend.setBackDate(new Date());
        if(bookService.updateById(book)&&lendService.updateById(lend)){
            return RespBean.success("归还成功！");
        }else{
            return RespBean.error("归还失败！");
        }
    }

    @PutMapping("/update")
    public RespBean update(@RequestBody Book book){
        if(bookService.updateById(book)){
            return RespBean.success("修改成功！");
        }else{
            return RespBean.error("修改失败！");
        }
    }

    @GetMapping("/findAll/{currentPage}/{size}")
    public Page<Book> findAll(@PathVariable("currentPage")Integer currentPage,@PathVariable("size")Integer size){
        return bookService.selectPage(currentPage,size);
    }

    @GetMapping("findById/{id}")
    public Book findById(@PathVariable("id")Integer id){
        return bookService.getById(id);
    }

    // 当前空闲图书查询
    @GetMapping("/findCan/{currentPage}/{size}")
    public Page<Book> findCan(@PathVariable("currentPage")Integer currentPage, @PathVariable("size")Integer size){
        return bookService.selectCanPage(currentPage,size);
    }

}
